package main

import (
	"fmt"
	"os"
	"time"
)

func duRunning(messageChan chan int) {
	//Ticker为定时器，可以每间隔一段时间把当前时间写入channel中，方便后续取用
	c := time.Tick(1 * time.Second)
	for {
		select {
		case <-messageChan:
			fmt.Println("收到外部消息，定时任务停止执行")
			return
		default:
			runningTime := <-c
			fmt.Printf("定时器任务,执行时间:%v\n", runningTime)
		}
	}
}

func cancelRunning(messageChan chan int) {
	_, err := os.Stdin.Read(make([]byte, 1))
	if err != nil {
		return
	}
	messageChan <- 1
}

func main() {
	messageChan := make(chan int)
	go duRunning(messageChan)
	go cancelRunning(messageChan)

	time.Sleep(100 * time.Second)
}
